<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="班级" prop="classId">
        <el-cascader
          class="w-full"
          v-model="formData.classId"
          :options="classList"
          :props="cascaderProps"
          clearable
          filterable
          placeholder="请选择班级"
          @change="handleClassChange"
        />
      </el-form-item>
      <el-form-item v-if="formData.classId" label="学生" prop="studentId">
        <el-select
          v-model="formData.studentId"
          :props="cascaderProps"
          placeholder="请选择学生"
          filterable
          clearable
        >
          <el-option
            v-for="item in studentList"
            :key="item.id"
            :label="item.studentName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="食物" prop="foodIds">
        <el-cascader
          class="w-full"
          popper-class="foods-cascader"
          v-model="foodIds"
          :options="foodTypeList"
          :props="foodCascaderProps"
          clearable
          filterable
          placeholder="请选择食物"
          max-collapse-tags-tooltip-height=""
          @change="handleFoodChange"
        />
      </el-form-item>

      <el-form-item label="过敏程度" prop="allergyLevel">
        <el-radio-group v-model="formData.allergyLevel">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_FOOD_ALLERGY)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { RecipeFoodAllergyApi, RecipeFoodAllergy } from '@/api/school/recipe/allergy'
import { RecipeFoodTypeApi } from '@/api/school/recipe/foodType'
import { RecipesApi } from '@/api/school/recipe/recipes'
import { defaultProps } from '@/utils/tree'
import { ClassesApi } from '@/api/school/classes'
import { StudentApi } from '@/api/school/student'
/** 食物过敏 表单 */
defineOptions({ name: 'RecipeFoodAllergyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData: any = ref({
  id: undefined,
  classId: undefined,
  studentId: undefined,
  foodIds: undefined,
  sort: undefined,
  allergyLevel: 0,
  status: 0
})
const formRules = reactive({
  classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
  studentId: [{ required: true, message: '学生不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const classList = ref([]) //班级列表
const studentList: any = ref([]) // 学生列表
const foodTypeList: any = ref([]) // 食物分类列表
const foodIds: any = ref([]) // 食物ID列表
const cascaderProps: any = computed(() => {
  return {
    ...defaultProps
  }
})

// 食物级联选择器属性
const foodCascaderProps: any = {
  ...defaultProps,
  multiple: true,
  lazy: true,
  lazyLoad: async (node, resolve) => {
    const { level, data } = node
    // 二级节点（食物）需要懒加载
    if (level === 1) {
      try {
        const list = await RecipesApi.getRecipeFoodList(data.sid)
        list.forEach((item) => {
          item.id = item.foodId
          item.name = item.foodName
          item.leaf = true
        })
        resolve(list)
      } catch (e) {
        console.error(e)
        resolve([])
      }
    } else {
      resolve([])
    }
  }
}

/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  defaultClassId?: number,
  defaultStudentId?: number
) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RecipeFoodAllergyApi.getRecipeFoodAllergy(id)
      foodIds.value = formData.value.foodId
      await handleClassChange(formData.value.classId, true)
    } finally {
      formLoading.value = false
    }
  }
  classList.value = await ClassesApi.getClassesList()
  foodTypeList.value = await RecipeFoodTypeApi.getSimpleRecipeFoodType()

  // 如果是新增操作且有默认的班级ID，则设置默认值
  if (type === 'create' && defaultClassId) {
    // 查找班级在级联选择器中的路径
    formData.value.classId = defaultClassId
    if (defaultStudentId) {
      formData.value.studentId = defaultStudentId
    }
    await handleClassChange(defaultClassId, true)
  }
}
const handleClassChange = async (id, needInit?: boolean) => {
  if (!needInit) {
    formData.value.studentId = undefined
  }
  if (!id) {
    studentList.value = []
  }
  const list = await StudentApi.getSimpleStudentList(id)
  studentList.value = list
}
const handleFoodChange = () => {
  if (formType.value === 'create') {
    formData.value.foodIds = foodIds.value.join(',')
  } else {
    formData.value.foodIds = foodIds.value
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RecipeFoodAllergy
    if (formType.value === 'create') {
      formData.value.foodIds = foodIds.value.join(',')
      await RecipeFoodAllergyApi.createRecipeFoodAllergy(data)
      message.success(t('common.createSuccess'))
    } else {
      formData.value.foodIds = foodIds.value
      delete formData.value.foodId
      delete formData.value.foodName
      await RecipeFoodAllergyApi.updateRecipeFoodAllergy(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    classId: undefined,
    studentId: undefined,
    foodIds: undefined,
    sort: undefined,
    allergyLevel: 0,
    status: 0
  }
  foodIds.value = []
  formRef.value?.resetFields()
}
</script>

<style lang="scss">
@import url('../style.scss');
</style>
